<template>
    <div class="app-container">
        <div class="search-container">
            <el-form v-show="showSearch" ref="queryParamsRef" :inline="true" :model="queryParams" label-width="80px">
                <el-form-item label="所属机构" v-if="!userInfo.orgId">
                    <select-org-tree :value="queryParams.orgId" @orgNodeClick="orgNodeClick" />
                </el-form-item>
                <el-form-item label="用户名称" prop="nickName">
                    <el-input v-model="queryParams.nickName" clearable placeholder="请输入用户名称"
                        @keyup.enter.native="handleQuery" />
                </el-form-item>
                <el-form-item label="工号" prop="userName">
                    <el-input v-model="queryParams.userName" clearable placeholder="请输入工号"
                        @keyup.enter.native="handleQuery" />
                </el-form-item>
                <div style="float: right" class="mr20">
                    <query-form-button @handleQuery="handleQuery" @resetQuery="resetQuery" />
                </div>
            </el-form>
        </div>
        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" @click="syncOrgPersonFun">
                    <svg-icon :icon-class="'xiafa'" class="mr5" />
                    同步机构人员
                </el-button>
                <el-button v-hasPerm="['base:drugPresPermissionsConf:export']" plain type="warning"
                    @click="handleExport"><template #icon>
                        <i-ep-download />
                    </template>导出
                </el-button>
            </el-col>
        </el-row>
        <el-row :gutter="20" class="div-height-left">
            <el-col :span="4" style="height: calc(100% - 42px);">
                <!--                     科室树-->
                <dept-tree ref="deptTreeRef" :org-id="queryParams.orgId" :height="'700px'" @treeClick="treeClick" />
            </el-col>
            <el-col :span="20" :xs="24">
                <el-table v-adaptive :data="drugPresPermissionsConfList" :border="true" highlight-current-row
                    :stripe="true" :header-cell-style="$headerCellStyle">
                    <el-table-column v-if="true" :show-overflow-tooltip="true" :align="'center'" fixed="left"
                        label="用户名称" prop="nickName" width="100" />
                    <el-table-column :show-overflow-tooltip="true" :align="'center'" fixed="left" label="工号"
                        prop="userName" width="80" />
                    <el-table-column :show-overflow-tooltip="true" :align="'center'" fixed="left" label="证件号码"
                        prop="certificateNo" width="140" />
                    <el-table-column :show-overflow-tooltip="true" :align="'left'" label="毒理分类" min-width="900"
                        prop="toxiProperty">
                        <template #default="scope">
                            <dict-data-tag :options="dictDataMap['drug_toxi_property_dict']"
                                :value="scope.row.toxiProperty ? scope.row.toxiProperty.split(',') : []" />
                        </template>
                    </el-table-column>
                    <el-table-column :show-overflow-tooltip="true" :align="'left'" label="限制等级" prop="limitClass"
                        width="280">
                        <template #default="scope">
                            <dict-data-tag :options="dictDataMap['limit_class_dict']"
                                :value="scope.row.limitClass ? scope.row.limitClass.split(',') : []" />
                        </template>
                    </el-table-column>
                    <!--                    <el-table-column :show-overflow-tooltip="true" label="备注信息" :align="'center'" prop="remarks"/>-->
                    <el-table-column :align="'center'" class-name="small-padding fixed-width" fixed="right" label="操作"
                        width="110">
                        <template #default="scope">
                            <el-button type="primary" @click="handleUpdate(scope.row)"><template #icon>
                                    <i-ep-edit />
                                </template>分配权限
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <pagination v-show="total > 0" v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageNum"
                    :total="total" @pagination="getList" />
            </el-col>
        </el-row>

        <!-- 添加或修改处方权限配置对话框 -->
        <el-dialog :close-on-click-modal="false" :title="title" v-model="open" append-to-body width="800px">
            <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
                <el-row :gutter="40">
                    <el-col :span="8">
                        <span class="el-form-item__label">用户名称：</span>
                        <span style="line-height: 40px;">{{ form.nickName }}</span>
                    </el-col>
                    <el-col :span="8">
                        <span class="el-form-item__label">工号：</span>
                        <span style="line-height: 40px;">{{ form.userName }}</span>
                    </el-col>
                    <el-col :span="8">
                        <span class="el-form-item__label">证件号：</span>
                        <span style="line-height: 40px;">{{ form.certificateNo }}</span>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="毒理分类">
                            <el-checkbox-group v-model="form.toxiProperty">
                                <el-checkbox v-for="dict in dictDataMap['drug_toxi_property_dict']"
                                    :key="dict.dictValue" :label="dict.dictValue">
                                    {{ dict.dictLabel }}
                                </el-checkbox>
                            </el-checkbox-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="限制等级">
                            <el-checkbox-group v-model="form.limitClass">
                                <el-checkbox v-for="dict in dictDataMap['limit_class_dict']" :key="dict.dictValue"
                                    :label="dict.dictValue">
                                    {{ dict.dictLabel }}
                                </el-checkbox>
                            </el-checkbox-group>
                        </el-form-item>
                    </el-col>
                    <!--                    <el-col :span="12">-->
                    <!--                        <el-form-item label="备注信息" prop="remarks">-->
                    <!--                            <el-input v-model="form.remarks" placeholder="请输入备注信息"/>-->
                    <!--                        </el-form-item>-->
                    <!--                    </el-col>-->
                </el-row>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup>
import {
    addDrugPresPermissionsConf,
    delDrugPresPermissionsConf,
    getDrugPresPermissionsConf,
    selectPageDrugPresPermissionsConf,
    syncOrgPerson,
    updateDrugPresPermissionsConf
} from "@/api/drug/drugPresPermissionsConf";
import selectOrgTree from "@/components/SysOrgTree/selectOrgTree.vue";
import {useDictStoreHook} from "@/store/modules/dict";
import {useUserStoreHook} from "@/store/modules/user";

const { proxy } = getCurrentInstance() as any
const formRef = ref()
const queryParamsRef = ref()
const dictStore = useDictStoreHook();
const deptTreeRef = ref()
const dictDataMap = ref<any>(dictStore.isTypeGetData('limit_class_dict', 'drug_toxi_property_dict'))
const useUserStore = useUserStoreHook();
// 登录用户信息
const userInfo = <UserInfoBusi>useUserStore.user.userInfo
// 按钮loading
const buttonLoading = ref(false)
// 选中数组
const ids = ref([])
// 非单个禁用
const single = ref(true)
// 非多个禁用
const multiple = ref(true)
// 显示搜索条件
const showSearch = ref(true)
// 总条数
const total = ref(0)
// 处方权限配置表格数据
const drugPresPermissionsConfList = ref<any>([])
// 弹出层标题
const title = ref("")
// 是否显示弹出层
const open = ref(false)
// 查询参数
const queryParams = ref<any>({
    pageNum: 1,
    pageSize: 10,
    userId: undefined,
    toxiProperty: undefined,
    limitClass: undefined,
    orgId: undefined,
    remarks: undefined
})
// 表单参数
const form = ref<any>({})
// 表单校验
const rules = ref({
    id: [
        { required: true, message: "主键不能为空", trigger: "blur" }
    ],
    userName: [
        { required: true, message: "用户名称不能为空", trigger: "blur" }
    ],
})

if (userInfo.orgId) {
    queryParams.value.orgId = userInfo.orgId
    getList()
}

// 机构树点击事件
function orgNodeClick(data, _e) {
    queryParams.value.orgId = data.orgId
    if (queryParams.value.orgId) {
        getList()
    }
}
/** 左侧科室树节点点击事件 */
function treeClick(obj) {
    queryParams.value.deptId = obj.id
    getList()
}
/** 查询处方权限配置列表 */
function getList() {
    if (!queryParams.value.orgId) {
        return ElMessage.error(proxy.$OrgIdIsEmpty)
    }
    selectPageDrugPresPermissionsConf(queryParams.value).then((response: any) => {
        drugPresPermissionsConfList.value = response.rows;
        total.value = response.total;
    });
}
// 取消按钮
function cancel() {
    open.value = false;
    reset();
}
// 表单重置
function reset() {
    form.value = {
        id: undefined,
        userId: undefined,
        toxiProperty: [],
        limitClass: [],
        orgId: undefined,
        delFlag: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        remarks: undefined
    };
}
/** 搜索按钮操作 */
function handleQuery() {
    queryParams.value.pageNum = 1;
    getList();
}
/** 重置按钮操作 */
function resetQuery() {
    queryParamsRef.value.resetFields()
    queryParams.value.deptId = ''
    // deptTreeRef.value.judgmentAllSelection('')
    handleQuery();
}
// 多选框选中数据
function handleSelectionChange(selection) {
    ids.value = selection.map(item => item.id)
    single.value = selection.length !== 1
    multiple.value = !selection.length
}
/** 新增按钮操作 */
function handleAdd() {
    reset();
    open.value = true;
    title.value = "添加处方权限配置";
}
/** 修改按钮操作 */
function handleUpdate(row) {
    reset();
    const permissionsConfId = row.permissionsConfId
    title.value = "配置处方权限配置";
    open.value = true;
    if (permissionsConfId.length > 0) {
        getDrugPresPermissionsConf(permissionsConfId).then((response: any) => {
            form.value = response.data;
            form.value.toxiProperty = form.value.toxiProperty ? form.value.toxiProperty.split(",") : [];
            form.value.limitClass = form.value.limitClass ? form.value.limitClass.split(",") : [];
            console.log("form.value",form.value)
        });
    } else {
        form.value.userId = row.userId
        form.value.orgId = row.orgId
        form.value.userName = row.userName
        form.value.nickName = row.nickName
        form.value.certificateNo = row.certificateNo
    }
}
/** 提交按钮 */
function submitForm() {
    (formRef.value as any).validate(valid => {
        if (valid) {
            buttonLoading.value = true;
            form.value.toxiProperty = form.value.toxiProperty ? form.value.toxiProperty.join(",") : '';
            form.value.limitClass = form.value.limitClass ? form.value.limitClass.join(",") : '';
            if (form.value.permissionsConfId != null) {
                updateDrugPresPermissionsConf(form.value).then(() => {
                    ElMessage.success("修改成功");
                    open.value = false;
                    getList();
                }).finally(() => {
                    buttonLoading.value = false;
                });
            } else {
                addDrugPresPermissionsConf(form.value).then(() => {
                    ElMessage.success("新增成功");
                    open.value = false;
                    getList();
                }).finally(() => {
                    buttonLoading.value = false;
                });
            }
        }
    });
}
/** 删除按钮操作 */
function handleDelete(row) {
    const idsThis = row.id || ids.value;
    ElMessageBox.confirm('是否确认删除处方权限配置编号为"' + idsThis + '"的数据项？',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        delDrugPresPermissionsConf(ids).then(() => {
            getList();
            ElMessage.success("删除成功");
        })
    }).catch(() => {
    })
}

/** 同步机构人员 */
function syncOrgPersonFun() {
    if (!queryParams.value.orgId) {
        return ElMessage.error(proxy.$OrgIdIsEmpty)
    }
    ElMessageBox.confirm('确定要进行人员同步吗？',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        syncOrgPerson(queryParams.value.orgId).then(() => {
            ElMessage.success("同步成功")
            getList()
        })
    }).catch(() => {
    })
}
/** 导出按钮操作 */
function handleExport() {
    // download('base/drugPresPermissionsConf/export', {
    //     ...queryParams
    // }, `drugPresPermissionsConf_${new Date().getTime()}.xlsx`)
}
</script>

<script lang="ts">
export default {
    name: "drugPresPermissionsConf"
}
</script>
